package com.jzo2o.market.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.market.dto.request.CouponUseReqDTO;
import com.jzo2o.api.market.dto.response.AvailableCouponsResDTO;
import com.jzo2o.api.market.dto.response.CouponUseResDTO;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.market.enums.CouponStatusEnum;
import com.jzo2o.market.mapper.CouponMapper;
import com.jzo2o.market.model.domain.Coupon;
import com.jzo2o.market.model.dto.request.CouponOperationPageQueryReqDTO;
import com.jzo2o.market.model.dto.request.SeizeCouponReqDTO;
import com.jzo2o.market.model.dto.response.CouponInfoResDTO;
import com.jzo2o.market.service.IActivityService;
import com.jzo2o.market.service.ICouponService;
import com.jzo2o.market.service.ICouponUseBackService;
import com.jzo2o.market.service.ICouponWriteOffService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageUtils;
import com.jzo2o.redis.utils.RedisSyncQueueUtils;
import com.xxl.job.core.context.XxlJobHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-09-16
 */
@Service
@Slf4j
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements ICouponService {

    @Resource(name = "seizeCouponScript")
    private DefaultRedisScript<String> seizeCouponScript;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private IActivityService activityService;

    @Resource
    private ICouponUseBackService couponUseBackService;

    @Resource
    private ICouponWriteOffService couponWriteOffService;


    @Override
    public  List<CouponInfoResDTO> selectMyCouponList(Integer status, Long lastId) {
        if (status > 3 || status < 1) {
            throw new BadRequestException("请求状态不存在");
        }
        Long id = UserContext.currentUser().getId();
        List<Coupon> couponList = lambdaQuery().eq(Coupon::getUserId, id)
                .eq(Coupon::getStatus, status)
                .lt(ObjectUtils.isNotNull(lastId),Coupon::getId,lastId)
                .orderByDesc(Coupon::getCreateTime)
                .last("limit 10")
                .list();
        if (CollUtils.isEmpty(couponList)) {
            return new ArrayList<>();
        }

        return BeanUtils.copyToList(couponList, CouponInfoResDTO.class);


    }
    //过期优惠卷定时失效
    @Override
    public void expire() {
        List<Coupon> coupons = lambdaQuery()
                .eq(Coupon::getStatus, CouponStatusEnum.NO_USE.getStatus())
                .lt(Coupon::getValidityTime, LocalDateTime.now())
                .list();
        if (CollUtils.isEmpty(coupons)) {
            XxlJobHelper.log("没有人拥有未使用的优惠卷！");
            return;
        }

        for (Coupon coupon : coupons) {
            lambdaUpdate()
                    .eq(Coupon::getId,coupon.getId())
                    .set(Coupon::getStatus, CouponStatusEnum.INVALID.getStatus())
                    .update();
        }

    }
    @Override
    public CouponUseResDTO use(CouponUseReqDTO couponUseReqDTO) {
        return null;
    }

    @Override
    public List<AvailableCouponsResDTO> getAvailable(BigDecimal totalAmount) {
        // 查询当前用户可用的优惠券
        Long userId = UserContext.currentUserId();
        List<Coupon> list = lambdaQuery()
                .eq(Coupon::getUserId, userId)
                .eq(Coupon::getStatus, CouponStatusEnum.NO_USE.getStatus())
                .gt(Coupon::getValidityTime, LocalDateTime.now())
                .le(Coupon::getAmountCondition, totalAmount)
                .list();
        // 判空
        if (CollUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
return null;
    }



    @Override
    public void seizeCoupon(SeizeCouponReqDTO seizeCouponReqDTO) {

    }

    @Override
    public PageResult<CouponInfoResDTO> queryForPageOfOperation(CouponOperationPageQueryReqDTO couponOperationPageQueryReqDTO) {
        // 1.数据校验
        if (ObjectUtils.isNull(couponOperationPageQueryReqDTO.getActivityId())) {
            throw new BadRequestException("请指定活动");
        }
        // 2.数据查询
        // 分页 排序
        Page<Coupon> couponQueryPage = PageUtils.parsePageQuery(couponOperationPageQueryReqDTO, Coupon.class);
        // 查询条件
        LambdaQueryWrapper<Coupon> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Coupon::getActivityId, couponOperationPageQueryReqDTO.getActivityId());
        // 查询数据
        Page<Coupon> couponPage = baseMapper.selectPage(couponQueryPage, lambdaQueryWrapper);

        // 3.数据转化，并返回
        return PageUtils.toPage(couponPage, CouponInfoResDTO.class);
    }

    @Override
    public List<CouponInfoResDTO> queryForList(Long lastId, Long userId, Integer status) {
        return null;
    }

    @Override
    public void revoke(Long activityId) {

    }

    @Override
    public Integer countReceiveNumByActivityId(Long activityId) {
        // 查询已领取的优惠券数量
        return lambdaQuery().eq(Coupon::getActivityId, activityId)
                .count();
    }

    @Override
    public void processExpireCoupon() {

    }
}
